<template>
<div style="display: flex;" >
  <div :style="{width: (isCollapse?'64px' : '208px')}">
    <el-menu :collapse="isCollapse"
             :collapse-transition="false"
             background-color="#545c64"
             text-color="#fff"
             active-text-color="#ff0"
             style="width: 100%;height: 100vh;"
             unique-opened
             router
             @select="selectMenu">
      <el-row style="padding-top: 10px;padding-bottom: 10px;">
        <el-col :span="3"></el-col>
        <el-col :span="1" style="padding-left:7px;"></el-col>
        <el-col :span="isCollapse?0:14"><span style="font-weight: bold;color: greenyellow">家政管理系统</span></el-col>
      </el-row>

      <el-sub-menu index="1">
        <template #title>
          <el-icon style="font-size: 21px;"><User/></el-icon> <span>员工功能</span>
        </template>
        <el-menu-item index="/empHome/workRecord">工作记录</el-menu-item>
        <el-menu-item index="/empHome/empFeedback">反馈服务</el-menu-item>
        <el-menu-item index="/empHome/empOrder">订单界面</el-menu-item>
        <el-menu-item index="/empHome/empWorkManager">管理工作记录</el-menu-item>
        <el-menu-item index="/empHome/empSession">客服会话界面</el-menu-item>
      </el-sub-menu>

      <el-sub-menu index="2">
        <template #title>
          <el-icon style="font-size: 21px;"><Avatar /></el-icon> <span>管理功能</span>
        </template>
        <el-menu-item index="/empHome/employee">员工管理</el-menu-item>
        <el-menu-item index="/empHome/customer">客户管理</el-menu-item>
        <el-menu-item index="/empHome/order">订单管理</el-menu-item>
        <el-menu-item index="/empHome/workManager">工作记录管理</el-menu-item>
        <el-menu-item index="/empHome/equipmentType">设备管理</el-menu-item>
        <el-menu-item index="/empHome/sessionAndMessage">会话管理</el-menu-item>
        <el-menu-item index="/empHome/dsService">服务管理</el-menu-item>
        <el-menu-item index="/empHome/advertisement">广告管理</el-menu-item>
        <el-menu-item index="/empHome/feedback">评价与反馈管理</el-menu-item>
        <el-menu-item index="/empHome/coupon">优惠券管理</el-menu-item>
        <el-menu-item index="/empHome/consumables">耗材管理</el-menu-item>
      </el-sub-menu>
      <el-sub-menu index="3">
        <template #title>
          <el-icon style="font-size: 21px;"><Grid /></el-icon> <span>核心管理</span>
        </template>
        <el-menu-item index="/empHome/department">部门管理</el-menu-item>
        <el-menu-item index="/empHome/contract">合同管理</el-menu-item>
        <el-menu-item index="/empHome/role">用户类型管理</el-menu-item>
        <el-menu-item index="/empHome/dict">字典管理</el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
  <div :style="{width: ( isCollapse ? 'calc(100% - 64px)' : 'calc(100% - 208px)' )}">
    <el-header style="height:10vh;background-color:#fff;padding-top:10px;">
      <el-row :gutter="10">
        <el-col :span="2">
          <el-button>
            <el-icon style="font-size:20px;" @click="changeCollapse"><Expand/></el-icon>
          </el-button>
        </el-col>
        <el-col :span="14">
          <el-breadcrumb separator="/" style="position:relative;top:10px;">
            <el-breadcrumb-item><a href="/empHome" style="font-size: 16px;font-weight: bold;">首页</a></el-breadcrumb-item>
            <el-breadcrumb-item v-for="item in breadcrumb">
              <span>{{item.label}}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-col>
        <el-col :span="6">
          <el-dropdown trigger="click" style="position: absolute;right: 20px">
            <el-button>
              {{saveEmployeeForm?saveEmployeeForm.username:''}}
              <el-icon><arrow-down/></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="userInfo">个人信息</el-dropdown-item>
                <el-dropdown-item @click="changePassword">修改用户名密码</el-dropdown-item>
                <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-header>
    <el-main style="height:90vh;padding:0;overflow-y: auto;">
      <el-tabs v-model="editableTabsValue" type="border-card" closable
               @tab-remove="removeTab" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in editableTabs" :label="item.title"
                     :name="item.name" >
          <router-view :key="item.name"/>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </div>
</div>
  <el-dialog title="个人信息" v-model="dialogVisible" style="width:1000px;padding:40px;">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input disabled v-model="saveEmployeeForm.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门">
            <el-select disabled v-model="saveEmployeeForm.deptId" placeholder="">
              <el-option v-for="item in deptArr" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input placeholder="请输入内容" v-model="saveEmployeeForm.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话号码">
            <el-input placeholder="请输入内容" v-model="saveEmployeeForm.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input placeholder="请输入内容" v-model="saveEmployeeForm.age"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别">
            <el-select v-model="saveEmployeeForm.gender">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select  disabled v-model="saveEmployeeForm.status">
              <el-option v-for="item in empStatus" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职级">
            <el-select disabled v-model="saveEmployeeForm.level" placeholder="">
              <el-option v-for="item in empLevelArr" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="上级">
            <el-input  disabled v-model="employeeArr.username"></el-input>
          </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名">
              <el-input disabled v-model="saveEmployeeForm.realName"></el-input>
            </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="住址">
            <el-input placeholder="请输入内容" v-model="saveEmployeeForm.address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="editEmployee">确定</el-button>
    </template>
  </el-dialog>

  <el-dialog title="修改用户名和密码" v-model="dialogVisible2" style="width:500px;padding:40px;">
    <el-form label-width="80px" label-position="top">
      <el-form-item label="用户名">
        <el-input placeholder="请输入内容" v-model="saveEmployeeForm2.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input placeholder="请输入内容" v-model="saveEmployeeForm2.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input placeholder="请输入内容" v-model="saveEmployeeForm2.password2" show-password></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose2">取消</el-button>
      <el-button type="primary" @click="editEmployee2">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {nextTick, onMounted, ref} from "vue";
import {ArrowDown} from "@element-plus/icons-vue";
import router from "@/router";
import axios from "axios";
import {ElMessage} from "element-plus";

const isCollapse=ref(false)
const url=ref('')
const editableTabsValue=ref()
const empLevelArr=ref([])
const editableTabs=ref([

])

const selectMenu = (index) => {
  if (document.querySelector('.el-menu-item')){
    nextTick(()=>{
      breadcrumb.value=map[index]
      const existingTab = editableTabs.value.find(tab => tab.name === index);
      if (!existingTab) {
        addTab(index);
      }
      editableTabsValue.value = index;
    },5)
  }else {
    console.log('Element is not available or has been removed.')
  }
}
const addTab = (index) => {
  const newTab={title:map[index][0].label,name:index}
  editableTabs.value.push(newTab)
}
const removeTab = (targetName) => {
  const tabs = editableTabs.value;
  let activeName = editableTabsValue.value;
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          activeName = nextTab.name;
        }
      }
    });
  }
  editableTabsValue.value = activeName;
  editableTabs.value = tabs.filter(tab => tab.name !== targetName);
};
const handleTabClick = (tab) => {
  breadcrumb.value=map[tab.props.name]
  editableTabsValue.value=tab.props.name
  navigateTo(editableTabsValue.value)
}
const navigateTo = (path) => {
  if (path.startsWith('/')) {
    router.push(path);
  }
};

const changePassword = () => {
  dialogVisible2.value=true;

}
const logout = () => {
  axios.get(BASE_URL+'/v1/employee/logout').then((response)=>{
    if (confirm('确定退出登录？')){
    if (response.data.code===2000){
      router.push('/empLogin')
    }else{
      ElMessage.error(response.data.msg)
    }
    }
  })
}
const userInfo = async () => {
  dialogVisible.value=true;
  await loadEmployee();
}
const changeCollapse = () => {
  isCollapse.value=!isCollapse.value
}
let map={
  '/empHome/dict': [{label: '字典管理'}],
  '/empHome/role': [{label: '用户类型管理'}],
  '/empHome/department': [{label: '部门管理'}],
  '/empHome/workRecord': [{label: '工作记录'}],
  '/empHome/workManager': [{label: '工作记录管理'}],
  '/empHome/empWorkManager': [{label: '管理工作记录'}],
  '/empHome/equipmentType': [{label: '设备管理'}],
  '/empHome/sessionAndMessage': [{label: '会话管理'}],
  '/empHome/customer': [{label: '客户管理'}],
  '/empHome/order': [{label: '订单管理'}],
  '/empHome/employee': [{label: '员工管理'}],
  '/empHome/dsService': [{label: '服务管理'}],
  '/empHome/contract': [{label: '合同管理'}],
  '/empHome/coupon': [{label: '优惠券管理'}],
  '/empHome/empFeedback': [{label: '员工端评价与反馈'}],
  '/empHome/feedback': [{label: '评价与反馈管理'}],
  '/empHome/consumables': [{label: '耗材管理'}],
  '/empHome/advertisement': [{label: '广告管理'}],
  '/empHome/empOrder': [{label: '订单界面'}],
  '/empHome/empSession': [{label: '客服会话界面'}],
}
const empStatus=ref([])
const breadcrumb= ref()
onMounted(async ()=>{
  try {
    await getEmp(saveEmployeeForm)
    if (Object.keys(saveEmployeeForm.value).length==0){
      router.push('/empLogin')

    }
    await loadDept();
    await loadDictOptions(empLevelArr,'EmpLevel');
    await loadDictOptions(empStatus,"EmpStatus");
  }catch (e) {
    console.log(e)
  }
})

const dialogVisible=ref(false);
const dialogVisible2=ref(false);
const saveEmployeeForm=ref({});
const saveEmployeeForm2=ref({});
const editEmployee = ()=>{
  axios.post(BASE_URL+'/v1/employee/save',saveEmployeeForm.value).then((response)=>{
    if(response.data.code==2000){
      ElMessage.success("保存成功！");
      dialogVisible.value=false;
      getEmp(saveEmployeeForm)
      //router.push('/empLogin')
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
const editEmployee2 = ()=>{
  if (confirm("确认要修改用户名密码吗?")){
  saveEmployeeForm2.value.id=saveEmployeeForm.value.id;
  if (saveEmployeeForm2.value.password!=saveEmployeeForm2.value.password2){
    ElMessage.error("两次密码不一致！");
    return;
  }
  axios.post(BASE_URL+'/v1/employee/save',saveEmployeeForm2.value).then((response)=>{
    if(response.data.code==2000){
      ElMessage.success("保存成功！");
      router.push('/empLogin')
    }else {
      ElMessage.error(response.data.msg);
    }
  })
  }
}
const handleClose=()=>{
  if (confirm("确定要关闭吗")){
    dialogVisible.value=false;
    saveEmployeeForm.value={};
  }
}
const handleClose2=()=>{
  if (confirm("确定要关闭吗")){
    dialogVisible2.value=false;
    saveEmployeeForm2.value={};
  }
}
const deptArr=ref([]);
const employeeArr=ref({});
const dept=ref({});

const loadDept = async () => {
  await axios.post(BASE_URL+'/v1/department/select',dept.value).then((response)=>{
    if(response.data.code==2000){
      deptArr.value = response.data.data;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
const loadEmployee = async () => {
  await axios.post(BASE_URL+'/v1/employee/select',{id:saveEmployeeForm.value.parentId}).then((response)=>{
    if(response.data.code==2000){
      if (response.data.data.length>0){
        employeeArr.value = response.data.data[0];
        console.log(employeeArr.value)
      }
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
</script>

<style scoped>

</style>